//#ifdef DESKTOP
core.WSTab = function(config){
	this.init(config);
}

core.extendClass('core.WSTab', 'core.Tab');

core.WSTab.prototype.init = function(config){
    config.cls = 'tab_taskbar_bg';
    this.superCall('init', arguments, config);
}

core.WSTab.prototype.onTimeout = function(aDraggable){
//	core.log(this.dropableCandidate, aDraggable);
	if(this.dropableCandidate==aDraggable && this.markedAsDropable){
//		core.log('ready to switch ws', this);
		core.desktop.taskbar.selectTab(this);
	}
}

core.WSTab.prototype.getDropTarget = function(aDraggable){
	if(this.timeout)
		core.clearTimeout(this.timeout);
	if(this.selected)
		return false;
    if(this.workspace.hasFrame(aDraggable.frame))
        return false;
	this.timeout = core.setTimeout(this, this.onTimeout, 1000, aDraggable);
	return this;
}
//#endif

core.Desktop = function(aParams){
	this.init(aParams);
}

//#ifdef DESKTOP
core.WINDOW_TITLE = 'Your workspace';
//#endif

//#ifdef MOBILE
core.WINDOW_TITLE = 'Your workspace (iPhone)';
//#endif

core.extendClass('core.Desktop', 'core.Box');

core.Desktop.prototype.init = function(aParams){
	this.xType = 'desktop';
    this.focused = true;
//	$(this.div).addClass('desktop');
//	this.padding = 5;
	this.dialogs = [];
	this.workspaces = [];
	var instance = this;
    this.bounced = false;
    this.notifies = 0;
    this.notifiesArr = [];
    document.title = core.WINDOW_TITLE;

    this.indicator = new core.NetworkIndicator({

    });

//#ifdef DESKTOP
	this.taskbar = new core.Tabs({
	});

	this.body = new core.Panel({
	});

    this.activeElement = this.body;

    this.rightDock = new core.dock.Dock({
        vertical: true
    });

//    var d = core.newDiv(null, 'dock_icon');
//    $(d).html('x');
//    d.side = 25;
//
//    this.rightDock.addDockElement(new core.dock.DockElement({
//        elements: d,
//        menu: [{
//                text: 'Menu01'
//        }]
//    }));
//
//    this.rightDock.addTab(new core.form.Button({
//        text: 'Button#2'
//    }));
//
//
    this.bottomDock = new core.dock.Dock({
        toolbar: true,
        cls: ' '
    });

    this.bottomPanel = new core.Box({
        colspan: 2,
        columns: '1, d, d',
        items: [this.taskbar, this.bottomDock, this.indicator]
    });

	this.superCall('init', arguments, {
		columns: '1, d',
		items: [this.body, this.rightDock, this.bottomPanel],
		rows: '1, d'
	});

    this.taskbar.on('select', function(i, e, tab){
        instance.showWorkspace(tab.workspace);
	});
    
//#endif
//#ifdef MOBILE
    this.body = new core.ws.FrameHolder({
		colspan: 4
    });
    
    this.status = new core.OneLineHelper({
        text: 'No events',
        align: 'left',
        valign: 'middle',
        icon_cls: 'desktop_icon info_icon',
        cls: 'mouse_over'
    });
    this.status.on('click', function(){
        instance.statusClick();
    })
    this.winList = new core.form.Button({
        icon: 'desktop_icon win_list_icon',
        handler: function(){
            instance.winListClick();
        }
    });
    this.appList = new core.form.Button({
        icon: 'desktop_icon app_list_icon',
        handler: function(){
            instance.appListClick();
        }
    });
	this.superCall('init', arguments, {
		columns: '1, d, d, d',
		items: [this.status, this.indicator, this.appList, this.winList, this.body],
		rows: 'd, 1'
	});
//#endif

    this.padding = 2;

    document.getElementById('desktop').appendChild(this.div);

    this.notifyBase = core.newDiv(this.div, 'notify_base');
    this.logDiv = core.newDiv(this.div, 'log');
    this.logContent = core.newDiv(this.logDiv, 'log_content');
    this.logExpanded = true;

    var expColl = function(){
        instance.logExpanded = !instance.logExpanded;
        $(instance.logDiv).width(instance.logExpanded?200:10).height(instance.logExpanded?200:10);
        return false;
    };
//    expColl();
    if(!DEBUG)
        $(this.logDiv).hide();
    else{
        $(this.logDiv).dblclick(expColl);
        $(this.logContent).dblclick(expColl);
    }
    this.updateLayout();
    core.desktop = this;
    core.setTimeout(this, this.refreshDesktop, 10);
//#ifdef DESKTOP
    $(window).resize(function(){
        core.desktop.refreshDesktop();
    });
    $(window).focus(function(){
//        core.log('gain: window');
        instance.focused = true;
        instance.stopBounce();
    }).blur(function(){
//        core.log('lost: window');
        instance.focused = false;
    });
    $(document).click(function(){
//        core.log('gain: document');
        instance.focused = true;
        instance.stopBounce();
    }).blur(function(){
//        core.log('lost: document');
        instance.focused = false;
    });
//#endif
}

core.Desktop.prototype.refreshDesktop = function(){
//    core.log('Resize: ', $(document.body).width(), $(document.body).height());
    core.desktop.doResize(0, 0, $(document.body).width(), $(document.body).height());
    $('#desktop').width(core.desktop.width).height(core.desktop.height);
};

core.Desktop.prototype.addLogEntry = function(aEntry){
    var set = $(this.logContent).children(':last');
    var y = 99999;
//    if(set.length>0){
//        y = set.position().top;
//        core.log('y is '+y);
//    }
//
    $(core.newDiv(this.logContent, 'log_entry')).html(aEntry);
    $(this.logContent).scrollTop(y);
};

core.Desktop.prototype.setWorkspaceTitle = function(aWorkspace, aCaption){
    if(aWorkspace.taskbarTab)
        aWorkspace.taskbarTab.setText(aCaption);
};

core.Desktop.prototype.showWorkspace = function(aWorkspace){
	for(var i = 0; i<this.workspaces.length; i++){
		if(this.workspaces[i]==aWorkspace){
            if(aWorkspace.floating){
                return this.raiseFloatWorkspace(aWorkspace);
            }
            this.activeWorkspace = aWorkspace;
            this.replaceChild(this.items[0], aWorkspace.root, core.REPLACE_CHILD_HIDE);
            this.activeElement = aWorkspace.root;
            aWorkspace.root.show();
            this.taskbar.selectTab(aWorkspace.taskbarTab);
            aWorkspace.showFrames();
            this.refresh(true);
            this.app.sendMessage('workspaceSelected', {
                workspace: aWorkspace.name
            });

            return true;
        }
	}
	return false;
}

//#ifdef DESKTOP
core.Desktop.prototype.getWorkspace = function(aWorkspaceName){
	for(var i = 0; i<this.workspaces.length; i++){
		if(this.workspaces[i].name==aWorkspaceName)
			return this.workspaces[i];
	}
    return null;
};

core.Desktop.prototype.hideFloatWorkspace = function(aWorkspace){
    if(aWorkspace.collapsed)
        return false;
    aWorkspace.root.hide();
    if(aWorkspace.floatDiv){
        $(aWorkspace.floatDiv).hide();
//        aWorkspace.floatDiv = null;
    }
    aWorkspace.collapsed = true;
    this.app.sendMessage('workspaceHidden', {
        workspace: aWorkspace.name
    });
    return true;
};

core.Desktop.prototype.resizeFloatDiv = function(aWorkspace, floatDiv){
    if(!floatDiv)
        floatDiv = aWorkspace.floatDiv;
    var y = aWorkspace.dockElement.bounds.y+5;
    var x = core.desktop.bottomDock.x+aWorkspace.dockElement.bounds.x;
    if(aWorkspace.vertical){
        x = core.desktop.activeElement.width-aWorkspace.width;
    }else{
        y = core.desktop.activeElement.height-aWorkspace.height;
    }

    if(x+aWorkspace.width>core.desktop.activeElement.width)
        x = core.desktop.activeElement.width-aWorkspace.width;
    if(y+aWorkspace.height>core.desktop.activeElement.height)
        y = core.desktop.activeElement.height-aWorkspace.height;
    if(x<0){
        x = 0;
        aWorkspace.width = core.desktop.activeElement.width;
    }
    if(y<0){
        y = 0;
        aWorkspace.height = core.desktop.activeElement.height;
    }
    $(floatDiv).width(aWorkspace.width).height(aWorkspace.height);
    $(aWorkspace.floatDivInner).
        css('left', core.dock.FLOAT_PANEL_BORDER).
        css('top', core.dock.FLOAT_PANEL_BORDER).
        width(aWorkspace.width-2*core.dock.FLOAT_PANEL_BORDER).
        height(aWorkspace.height-2*core.dock.FLOAT_PANEL_BORDER);
    $(floatDiv).css('left', x).css('top', y);
    return {
        x: x,
        y: y,
        width: aWorkspace.width,
        height: aWorkspace.height
    };
};

core.Desktop.prototype.raiseFloatWorkspace = function(aWorkspace){
//    core.log('raiseFloatWorkspace', aWorkspace);
    var instance = this;
    for (var i = 0; i < this.workspaces.length; i++) {
        var ws = this.workspaces[i];
        if(!ws.collapsed && ws.floating){
            if(ws==aWorkspace)
                return true;
            this.hideFloatWorkspace(ws);
        }
    }
//    core.log('Raising 0');
//    $(aWorkspace.floatDiv).hide();
//    core.log('show ws ', aWorkspace.vertical, aWorkspace.x, aWorkspace.y, aWorkspace.bounds.x, aWorkspace.bounds.y);
    var floatDiv = core.newDiv(core.desktop.div, 'float_ws');
    aWorkspace.floatDivInner = core.newDiv(floatDiv, 'float_ws_inner');
//    core.log('floatDiv x', x);
    this.resizeFloatDiv(aWorkspace, floatDiv);
    $(floatDiv).show();
    $(aWorkspace.root.div).appendTo(aWorkspace.floatDivInner);
    if(aWorkspace.floatDiv)
        $(aWorkspace.floatDiv).remove();
    aWorkspace.floatDiv = floatDiv;
    aWorkspace.root.show();
    aWorkspace.showFrames();
    aWorkspace.root.doResize(0, 0, $(aWorkspace.floatDivInner).width(), $(aWorkspace.floatDivInner).height());
    aWorkspace.collapsed = false;
    this.app.sendMessage('workspaceRaized', {
        workspace: aWorkspace.name
    });
    var resizeHandler = function(aDim){
//        core.log('resize ws to ', aDim.width, aDim.height);
        aWorkspace.width = aDim.width;
        aWorkspace.height = aDim.height;
        instance.resizeFloatDiv(aWorkspace);
        aWorkspace.root.doResize(0, 0, $(aWorkspace.floatDivInner).width(), $(aWorkspace.floatDivInner).height());
        instance.app.sendMessage('workspaceResized', {
            workspace: aWorkspace.name,
            width: aWorkspace.width,
            height: aWorkspace.height
        });
    };
    if(aWorkspace.vertical){
        core.resize.enableResize({
            div: floatDiv,
            handler: resizeHandler,
            left: true,
            bottom: true
        });
    }else{
        core.resize.enableResize({
            div: floatDiv,
            handler: resizeHandler,
            top: true,
            right: true
        });
    }
    return true;
};

core.Desktop.prototype.addWorkspace = function(aWorkspace, aPosition){
	for(var i = 0; i<this.workspaces.length; i++){
		if(this.workspaces[i].name==aWorkspace.name)
			return false;
	}
    var pos = aPosition || this.workspaces.length;
//    core.log('Insert ws at '+pos, this.workspaces.length);
    this.workspaces.splice(pos, 0, aWorkspace);
//    core.log('Insert ws at '+pos, this.workspaces.length);
//	this.workspaces.push(aWorkspace);
    if(aWorkspace.floating){
        //Add floating workspace
        var dockElement = new core.dock.DockElement({
            vertical: aWorkspace.vertical
        });
        aWorkspace.dockElement = dockElement;
        if(aWorkspace.application)
            aWorkspace.application.loadDockIndicator(aWorkspace);
        aWorkspace.dockElement.on('click', function(){
            //Collapse/expand
//            aWorkspace.collapsed = !aWorkspace.collapsed;
//            core.log('float ws collapsed: ', aWorkspace.collapsed);
            if(aWorkspace.collapsed){
                core.desktop.raiseFloatWorkspace(aWorkspace);
            }else{
                core.desktop.hideFloatWorkspace(aWorkspace);            }
        });
        var dock = aWorkspace.vertical?this.rightDock : this.bottomDock;
        aWorkspace.dock = dock;
        dock.addDockElement(aWorkspace.dockElement);
        if(!aWorkspace.collapsed){
            aWorkspace.collapsed = true;
            this.raiseFloatWorkspace(aWorkspace);
        }
    }else{
        var tabMenu = [{
                text: 'Reset workspace',
                handler: function(item, tab){
                    core.desktop.app.sendMessage('resetWorkspace', {
                        workspace: tab.workspace.name
                    }, null, null, core.desktop);
                    return true;
                }
        }]
        var tab = new core.WSTab({
            text: aWorkspace.caption,
            menu: tabMenu,
            menuOwner: this.bottomPanel,
            closeable: aWorkspace.closeable
        });
        tab.on('close', function(tab, e){
            core.desktop.app.sendMessage('workspaceClosing', {
                workspace: tab.workspace.name
            }, null, null, tab);
        });
        tab.workspace = aWorkspace;
        aWorkspace.taskbarTab = tab;

        this.taskbar.addTab(tab);
    }

    return true;
};
//#endif

core.HOME_PAGE = 'http://code.google.com/p/be-organized/wiki/lab';

core.Desktop.prototype.displayLogin = function(aLogin, aPassword){
    var login = new core.form.TextField({
        text: aLogin
    });
    var password = new core.form.TextField({
        password: true,
        text: aPassword
    });
    var okBtn = new core.form.Button({
       text: 'Login',
       align: 'center',
       colspan: 2,
       handler: function(){
           dlg.markLoading();
           core.net.request('session', {
               login: login.getValue(),
               password: password.getValue(),
               session_type: PLATFORM
           }, function(aData){
               core.desktop.closeDialog(dlg);
//               core.log('Token is', aData.token);
//               core.desktop.markLoading();
               core.net.token = aData.token;
               core.net.startLink();
           }, function(code, error){
//               core.log('Error: '+error);
               dlg.unMarkLoading();
               core.JSApplication.prototype.showError(error, 'Error:', function(){
                   login.doFocus();
               });
           });
       }
    });
    var loginLbl = new core.Label({
        text: 'Login name:',
        align: 'right'
    });
    var passLbl = new core.Label({
        text: 'Password:',
        align: 'right'
    });
    var welcome = new core.Label({
        colspan: 2,
        align: 'left',
        text: 'Soft registration: enter any login name and password to create new or connect to existing session'
    });
    var switchLbl = new core.Label({
//#ifdef DESKTOP
        text: 'Switch to <a href="m.html">mobile version</a>',
//#endif
//#ifdef MOBILE
        text: 'Switch to <a href="desktop.html">desktop version</a>',
//#endif
        align: 'left'
    });
    var homePageLbl = new core.Label({
        text: 'Go to <a href="'+core.HOME_PAGE+'" target="_blank">project page</a>',
        align: 'right'
    });
    var dlg = new core.Dialog({
        title: 'Welcome!',
        items: [welcome, loginLbl, login, passLbl, password, okBtn,
            new core.Box({
                colspan: 2,
                items: [switchLbl, homePageLbl],
                columns: '1, 1'
            })],
        rows: '5xd',
        columns: '0.3, 0.7',
        maxWidth: 400
    });
    core.desktop.showDialog(dlg);
    login.doFocus();
    $('#loading').remove();
};

//#ifdef DESKTOP
core.Desktop.prototype.removeWorkspace = function(aWorkspace){
//    core.log('removews', aWorkspace);
	for(var i = 0; i<this.workspaces.length; i++){
		if(this.workspaces[i]==aWorkspace){
//            core.log('removing tab',aWorkspace.taskbarTab);
            if(aWorkspace.floating){
                //Remove dockElement
                this.hideFloatWorkspace(aWorkspace);
                aWorkspace.dock.removeDockElement(aWorkspace.dockElement);
                aWorkspace.dock.refresh();
            }else{
                this.taskbar.removeTab(aWorkspace.taskbarTab);
                this.taskbar.refresh();
            }
            this.workspaces.splice(i, 1);
            return true;
        }
	}
    return false;
};
//#endif

core.Desktop.prototype.setFocusedPanel = function(aPanel){
//    core.log('Set focused panel', aPanel.instanceID);
    if(this.focusedPanel==aPanel)
        return false;
    if(this.focusedPanel)
        this.focusedPanel.unfocus();
    this.focusedPanel = aPanel;
    return true;
}

core.Desktop.prototype.processKeyDown = function(e){
	if(this.dialogs.length>0)
        return this.dialogs[this.dialogs.length-1].processKeyDown(e);
    for (var i = 0; i < this.workspaces.length; i++) {
        var ws = this.workspaces[i];
        if(!ws.collapsed && ws.floating){
            var res = ws.root.processKeyDown(e);
            if(!res)
                return false;
        }
    }
	return this.superCall('processKeyDown', arguments, e);
}

core.Desktop.prototype.closeDialog = function(aDialog){
	if(this.dialogs.length==0)
		return;
	for(var i = 0; i<this.dialogs.length; i++){
		if(this.dialogs[i]==aDialog){
			this.dialogs.splice(i, 1);
			$(aDialog.div).remove();
            if(i>0){
                this.dialogs[i-1].body.focus();
            }
			break;
		}
	}
//	core.log(this.dialogs.length);
	if(this.dialogs.length==0){
		$(this.dDiv).remove();
		this.dDiv = null;
	}
}

core.Desktop.prototype.showDialog = function(aDialog){
	if(this.dialogs.length==0){
		//Create dim div
		this.dDiv = core.newDiv(this.div, 'desktop_disable');
		$(this.dDiv).mousedown(function(){
			return false;
		});
//		$(this.dDiv).width(this.bounds.width);
//		$(this.dDiv).height(this.bounds.height);
//		$(this.dDiv).fadeTo(1, 0.2);
	}
	this.reParent(aDialog);
	aDialog.updateLayout();
	this.dialogs.push(aDialog);
	
	this.refreshDesktop();
}
core.Desktop.prototype.getMinHeight = function(){
    var minh = this.superCall('getMinHeight', arguments);
    var aWidth = this.width;
	for(var i = 0; i<this.dialogs.length; i++){
		var d = this.dialogs[i];
		var minWidth = d.getMinWidth();
		var width = d.maxWidth;
		if(width<minWidth)
			width = minWidth;
		if(width>aWidth)
			width = aWidth;
		d.setWidth(width);
		var minHeight = d.getMinHeight();
//        core.log('dialog minheight: '+minh, minHeight);
        d.setHeight(minHeight);
        if(minHeight>minh)
            minh = minHeight;
	}
//    core.log('dialog minheight: '+minh);
    this.minHeight = minh;
    return minh;
};

core.Desktop.prototype.makeResize = function(aX, aY, aWidth, aHeight){
	if(this.dDiv){
		$(this.dDiv).width(aWidth);
		$(this.dDiv).height(aHeight);
	}
	for(var i = 0; i<this.dialogs.length; i++){
		var d = this.dialogs[i];
		d.show();
        var width = d.width;
        var height = d.height;
//        core.log('window scroll = '+$(window).scrollTop());
//#ifdef DESKTOP
		d.resize(Math.floor((aWidth-width)/2), Math.floor((aHeight-height)/2), width, height);
//#endif

//#ifdef MOBILE
        var y = $(window).scrollTop();
        if(y<25)
            y = 25;
        if(y+height>aHeight)
            y = aHeight-height;
		d.resize(Math.floor((aWidth-width)/2), y, width, height);
//#endif
	}
//#ifdef DESKTOP
    for (var i = 0; i < this.workspaces.length; i++) {
        var ws = this.workspaces[i];
        if(!ws.collapsed && ws.floating){
            this.resizeFloatDiv(ws);
            ws.root.doResize(0, 0, $(ws.floatDivInner).width(), $(ws.floatDivInner).height());
        }
    }

//#endif
}

//#ifdef DESKTOP

core.Desktop.prototype.toggleBounce = function(aFlag){
    document.title = (aFlag?'['+this.notifies+'] ':'')+core.WINDOW_TITLE;
    this.bounceID = core.setTimeout(this, this.toggleBounce, 1000, !aFlag);
};

core.Desktop.prototype.startBounce = function(){
    this.notifies++;
    if(!this.bounced){
        this.bounced = true;
        this.bounceID = core.setTimeout(this, this.toggleBounce, 1000, true);
    }
}

core.Desktop.prototype.stopBounce = function(){
    this.notifies = 0;
    this.bounced = false;
    clearTimeout(this.bounceID);
    document.title = core.WINDOW_TITLE;
}

core.Desktop.prototype.addNotify = function(aNotify){
    var instance = this;
    var main = core.newDiv(this.notifyBase, 'notify');
    var header = new core.OneLineHelper({
        text: aNotify.date+aNotify.header,
        icon_cls: aNotify.icon || 'desktop_icon info_icon',
        cls: 'notify_header'
    });
    $(header.div).appendTo(main);
    var text = core.newDiv(main, 'notify_text');
    header.resize(0, 3, $(main).width(), 20);
    $(text).html(aNotify.text);
    main.oncontextmenu = function(){
        return false;
    };
    $(main).mousedown(function(e){
        var rightClick = $.browser.opera?(e.shiftKey && e.which==1):(e.which==3);
        if(!rightClick)
            instance.app.showFrame(aNotify);
        $(this).slideUp(300, function(){
            $(this).remove();
        });
        if(!rightClick)
            instance.app.showFrame(aNotify);
    });
//    core.log('addNotify', this.focused, aNotify.timeout);
    var timeout = aNotify.timeout || 0;
    if(!this.focused && !aNotify.forceAutoRemove){
        timeout = 0;
        this.startBounce();
    }
    if(timeout>0){
        setTimeout(function(){
//            core.log('Hide by timeout');
            $(main).slideUp(300, function(){
                $(this).remove();
            });
        }, timeout);
    }
};
//#endif

//#ifdef MOBILE
core.Desktop.prototype.closeMenu = function(aMenu){
    var result = false;
    if(this.nMenu){
        if(aMenu==this.nMenu)
            result = true;
        this.nMenu.hideMenu();
        this.nMenu = null;
    }
    if(this.wMenu){
        if(aMenu==this.wMenu)
            result = true;
        this.wMenu.hideMenu();
        this.wMenu = null;
    }
    if(this.aMenu){
        if(aMenu==this.aMenu)
            result = true;
        this.aMenu.hideMenu();
        this.aMenu = null;
    }
    return result;
};

core.Desktop.prototype.appListClick = function(){
    if(this.closeMenu(this.aMenu))
        return;
    var instance = this;
    var menu = [];
    for (var i = 0; i < core.desktop.apps.length; i++) {
        var app = core.desktop.apps[i];
        menu.push({
            text: app.name,
            cls: app.icon,
            app: app.code,
            index: i,
            handler: function(item){
                instance.closeMenu();
                instance.app.send({
                    method: 'showApplication',
                    message:{
                        app: item.app
                    },
                    disable: core.desktop
                });
                core.desktop.apps.splice(item.index, 1);
                if(core.desktop.apps.length==0)
                    instance.appList.setDisabled(true);
                return true;
            }
        });
    }
    this.aMenu = core.showMenu(this.appList, menu, true, false);
};

core.Desktop.prototype.winListClick = function(){
    if(this.closeMenu(this.wMenu))
        return;
    this.closeMenu();
    var instance = this;
    var menu = [];
    for (var i = 0; i < core.desktop.body.frames.length; i++) {
        var frame = core.desktop.body.frames[i];
        menu.push({
            text: frame.title,
            cls: frame.icon,
            frame: frame,
            handler: function(item){
                instance.closeMenu();
                core.desktop.body.showFrame(item.frame);
                return true;
            }
        });
    }
    this.wMenu = core.showMenu(this.winList, menu, true, false);
};

core.Desktop.prototype.statusClick = function(){
    this.closeMenu();
    var instance = this;
    if(this.notifies>0){
        var menu = [];
        for (i = 0; i < this.notifiesArr.length; i++) {
            var n = this.notifiesArr[i];
            menu.push({
                text: n.date+n.header,
                cls: n.icon,
                notify: n,
                handler: function(item){
                    instance.closeMenu();
                    instance.app.showFrame(item.notify);
                    return true;
                }
            });
        }
        this.nMenu = core.showMenu(this.status, menu, true, false);
        this.status.setText('No events');
        this.status.icon_cls = 'desktop_icon info_icon';
        this.notifiesArr = [];
        this.status.refresh();
        this.notifies = 0;
    }
};

core.Desktop.prototype.addNotify = function(aNotify){
    if(aNotify.forceAutoRemove)
        return;
    this.notifies++;
    this.status.setText('['+this.notifies+'] '+aNotify.date+aNotify.header);
    this.status.icon_cls = aNotify.icon;
    this.notifiesArr.push(aNotify);
    this.status.refresh();
};
//#endif

//#ifdef DESKTOP
core.SplittedPanel = function(config){
	this.init(config);
};

core.extendClass('core.SplittedPanel', 'core.Box');

core.SplittedPanel.prototype.processKeyDown = function(e){
	if(this.leftElement && !this.leftElement.processKeyDown(e))
		return false;	
	if(this.rightElement && !this.rightElement.processKeyDown(e))
		return false;
	return true;
}
core.SplittedPanel.prototype.replaceChild = function(aOldChild, aChild, aDestroyChild){
	if(!aDestroyChild)
		aDestroyChild = core.REPLACE_CHILD_HIDE;
	if(aOldChild==this.leftElement){
		if(aDestroyChild==core.REPLACE_CHILD_DESTROY)
			this.leftElement.destroy();
		if(aDestroyChild==core.REPLACE_CHILD_HIDE)
			this.leftElement.hide();
		this.setLeftElement(aChild);
	}
	if(aOldChild==this.rightElement){
		if(aDestroyChild==core.REPLACE_CHILD_DESTROY)
			this.rightElement.destroy();
		if(aDestroyChild==core.REPLACE_CHILD_HIDE)
			this.rightElement.hide();
		this.setRightElement(aChild);
	}
}
core.SplittedPanel.prototype.updateLayout = function(){
	if(this.leftElement)
		this.leftElement.updateLayout();
	if(this.rightElement)
		this.rightElement.updateLayout();
}

core.SplittedPanel.prototype.stopResize = function(aFixResults, aX, aY){
	$(this.moveLayer).remove();
	if(aFixResults){
		if(this.horizontal)
			this.divider = this.bounds.height==0?1:(this.leftSize-(this.mouseY-aY))/this.bounds.height;
		else
			this.divider = this.bounds.width==0?1:(this.leftSize-(this.mouseX-aX))/this.bounds.width;
//        core.log('divider:', this.divider, this.name);
        core.desktop.app.sendMessage('dividerMoved', {
            divider: this.divider,
            name: this.name,
            workspace: this.workspace.name
        });
	}
    this.setDirty();
	this.resize(this.bounds.x, this.bounds.y, this.bounds.width, this.bounds.height);
}

core.SplittedPanel.prototype.moveDivider = function(aX, aY){
	if(this.horizontal){
//		core.log('mouseCoords2: ', aX, aY);
		var newCoord = this.leftSize-(this.mouseY-aY);
		if(newCoord<0)
			newCoord = 0;
		if(newCoord+SPLITTER_WIDTH>this.bounds.height)
			newCoord = this.bounds.height-SPLITTER_WIDTH;
		$(this.dividerDiv).css('top', newCoord);
	}else{
		var newCoord = this.leftSize-(this.mouseX-aX);
		if(newCoord<0)
			newCoord = 0;
		if(newCoord+SPLITTER_WIDTH>this.bounds.width)
			newCoord = this.bounds.width-SPLITTER_WIDTH;
		$(this.dividerDiv).css('left', newCoord);
	}
}

core.SplittedPanel.prototype.startMoveDivider = function(){
//	core.log('mouseCoords: ', this.mouseX, this.mouseY);
	$(this.dividerDiv).appendTo(this.div);
	this.moveLayer = core.newDiv(this.div, 'split_layer');
	$(this.moveLayer).width(this.bounds.width);
	$(this.moveLayer).height(this.bounds.height);
	$(this.moveLayer).css('cursor', this.horizontal?'row-resize':'col-resize');
	$(this.moveLayer).fadeTo(1, 0.1, function(){
		$(this).show();
	});
	var instance = this;
	$(this.moveLayer).mousemove(function(e){
//		core.log('mousemove', e);
		instance.moveDivider(e.clientX, e.clientY);
	});
	$(this.moveLayer).mouseout(function(e){
		instance.stopResize();
		return false;
	});
	$(this.moveLayer).mouseup(function(e){
//		core.log('mouseup', e);
		instance.stopResize(true, e.clientX, e.clientY);
		return false;
	});
}

core.SplittedPanel.prototype.init = function(config){
	this.xType = 'sppanel';
	this.superCall('init', arguments, config);
    this.name = config.name || ('sp'+(core.idInc++));
    this.workspace = config.workspace;
	var instance = this;
	this.divider = config.divider || 0.5;
	this.horizontal = !config.vertical;
	this.dividerDiv = core.newDiv(this.div, 'splitter');
	$(this.dividerDiv).css('cursor', this.horizontal?'row-resize':'col-resize');
	if(config.leftElement)
		this.setLeftElement(config.leftElement);
	if(config.rightElement)
		this.setRightElement(config.rightElement);
	$(this.dividerDiv).mousedown(function(e){
		instance.mouseX = e.clientX;
		instance.mouseY = e.clientY;
		instance.startMoveDivider();
		return false;
	});
};

core.SplittedPanel.prototype.getNeighbour = function(aElement){
	if(aElement==this.leftElement)
		return this.rightElement;
	if(aElement==this.rightElement)
		return this.leftElement;
	return null;
}

core.SplittedPanel.prototype.setLeftElement = function(aElement){
	this.leftElement = aElement;
	if(aElement)
		this.reParent(aElement);
}

core.SplittedPanel.prototype.setRightElement = function(aElement){
	this.rightElement = aElement;
	if(aElement)
		this.reParent(aElement);
}

core.SplittedPanel.prototype.getDropTarget = function(aDraggable, aX, aY){
	if(this.horizontal){
		if(this.leftElement && aY<=this.leftSize)
			return this.leftElement.getDropTarget(aDraggable, aX, aY);
		if(this.rightElement && aY>=this.leftSize+SPLITTER_WIDTH);
			return this.rightElement.getDropTarget(aDraggable, aX, aY-this.leftSize-SPLITTER_WIDTH);
	}else{
		if(this.leftElement && aX<=this.leftSize)
			return this.leftElement.getDropTarget(aDraggable, aX, aY);
		if(this.rightElement && aX>=this.leftSize+SPLITTER_WIDTH);
			return this.rightElement.getDropTarget(aDraggable, aX-this.leftSize-SPLITTER_WIDTH, aY);		
	}
	return null;
}

core.SplittedPanel.prototype.setDirty = function(){
    this.dirty = true;
    if(this.leftElement)
        this.leftElement.setDirty();
    if(this.rightElement)
        this.rightElement.setDirty();
}

core.SplittedPanel.prototype.makeResize = function(aX, aY, aWidth, aHeight){
//	core.log('resize', this.className, this.instanceID, aX, aY, aWidth, aHeight);
	var sizeToDivide = this.horizontal?aHeight:aWidth;
	if(this.divider>1)
		this.divider = 1;
	if(this.divider<=0)
		this.divider = 0;
	var leftSize = Math.floor((sizeToDivide)*this.divider);
	var rightSize = sizeToDivide-SPLITTER_WIDTH-leftSize;
	if(leftSize+SPLITTER_WIDTH>sizeToDivide)
		leftSize = sizeToDivide-SPLITTER_WIDTH;
	if(rightSize+SPLITTER_WIDTH>sizeToDivide)
		rightSize = sizeToDivide-SPLITTER_WIDTH;
	this.leftSize = leftSize;
	if(this.horizontal){
		if(this.leftElement){
			this.leftElement.doResize(0, 0, aWidth, leftSize);
		}
		if(this.rightElement){
			this.rightElement.doResize(0, leftSize+SPLITTER_WIDTH, aWidth, rightSize);
		}
		$(this.dividerDiv).css('left', 0);
		$(this.dividerDiv).css('top', leftSize);
		$(this.dividerDiv).width(aWidth);
		$(this.dividerDiv).height(SPLITTER_WIDTH);
	}else{
		if(this.leftElement){
			this.leftElement.doResize(0, 0, leftSize, aHeight);
		}
		if(this.rightElement){
			this.rightElement.doResize(leftSize+SPLITTER_WIDTH, 0, rightSize, aHeight);
		}
		$(this.dividerDiv).css('left', leftSize);
		$(this.dividerDiv).css('top', 0);
		$(this.dividerDiv).width(SPLITTER_WIDTH);
		$(this.dividerDiv).height(aHeight);		
	}
}
//#endif
core.Dialog = function(config){
	this.init(config);
}

core.extendClass('core.Dialog', 'core.Box');

core.Dialog.prototype.init = function(config){
	this.xType = 'dialog';
	this.title = new core.OneLineHelper({
		text: config.title || 'Untitled dialog:',
		cls: 'dialog_title',
		parent: this
	});
	this.title.minHeight = 20;
    this.defaultItem = config.defaultItem;
//    core.log('Creating dialog body...', config.rows, config.columns, config.items.length);
	this.body = new core.Panel({
		rows: config.rows,
		columns: config.columns,
		items: config.items
	});
//    core.log('Creating dialog body finished');
	this.reParent(this.body);
	
	this.superCall('init', arguments, {
		columns: '1',
		rows: 'd, 1',
		items: [this.title, this.body]
	});
	
	this.align = config.align || 'center';
	this.valign = config.align || 'middle';
	this.maxWidth = config.maxWidth || 100;
	this.maxHeight = config.maxHeight || 100;
	$(this.div).addClass('dialog');
//    core.log('Filling data...');
    if(config.data){
        this.body.setValue(config.data);
    }
}

core.NetworkIndicator = function(config){
    this.init(config);
};


core.extendClass('core.NetworkIndicator', 'core.Box');

core.NetworkIndicator.prototype.init = function(config){
    this.xType = 'network';
    this.superCall('init', arguments, config);
    this.minWidth = 30;
    this.minHeight = 25;
    this.divIn = core.newDiv(this.div, 'desktop_icon network_in');
};

core.NetworkIndicator.prototype.setIndicator = function(aActive){
    if(aActive)
        $(this.divIn).addClass('network_do');
    else
        $(this.divIn).removeClass('network_do');
}
